// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package file

import (
	"audio-server/internal/model"
	"audio-server/internal/result"
	"audio-server/internal/svc"
	"audio-server/internal/types"
	"context"
	"database/sql"
	"encoding/json"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type FileAddTagLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFileAddTagLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileAddTagLogic {
	return &FileAddTagLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FileAddTagLogic) FileAddTag(req *types.FileAddTagReq) (resp *types.BaseMsgResp, err error) {
	id := req.FileId
	names := req.TagNames
	fileModel := model.NewSysFileModel(l.svcCtx.Conn)
	file, err := fileModel.FindOne(l.ctx, id)
	if err != nil {
		return result.Fail("文件不存在"), nil
	}
	jsonData, err := json.MarshalIndent(names, "", "  ")
	if err != nil {
		return result.Fail("转换失败"), nil
	}
	file.Tags = sql.NullString{String: string(jsonData), Valid: true}
	err = fileModel.Update(l.ctx, file)
	if err != nil {
		return result.Fail("更新文件失败"), nil
	}
	tagModel := model.NewSysFileTagModel(l.svcCtx.Conn)

	for _, name := range names {
		if name == "" {
			// 处理空标签名称
			continue // 或者返回错误
		}
		_, err := tagModel.Insert(l.ctx, &model.SysFileTag{
			Title:      name,
			CreateTime: time.Now(),
		})
		if err != nil {
			continue
		}
	}

	return result.Success(nil), nil
	// todo: add your logic here and delete this line

}
